const log4js = require('koa-log4');
const logger = log4js.getLogger('routes::city');
const pinyin = require("pinyin");

const router = require('koa-router')();
exports = module.exports = router;

const util = require(global.prefixPath + '/commons/util');
const city_service = require(global.prefixPath + '/services/city');

router.get('/cities', async (ctx, next) => {
    try {
        let result = await city_service.findAll();
        ctx.body = result;
    } catch (err) {
        throw err;
    }
});

router.get('/city/:key', async (ctx, next) => {
    try {
        let city_key = ctx.params.key;

        console.log('----------------- city_id -----------------');
        console.log(city_key);
        console.log('----------------- city_id -----------------');
        if (util.isObjectID(city_key)) {
            let result = await city_service.findById(city_key);
            ctx.body = result;
        } else {
            let result = await city_service.findByPinyin(city_key);
            ctx.body = result;
        }
    } catch (err) {
        throw err;
    }
});

// 拼音比较方便
// router.get('/city/:pinyin', async (ctx, next) => {
//     try {
//         let pinyin = ctx.params.pinyin;
//         let result = await city_service.findByPinyin(pinyin);
//         ctx.body = result;
//     } catch (err) {
//         throw err;
//     }
// });

router.post('/city', async (ctx, next) => {
    try {
        let city = ctx.request.body;
        city.pinyin = pinyin(city.name, {style: pinyin.STYLE_NORMAL}).join("");
        let city_data = await util.getCityData(city.pinyin);
        city.subways = city_data.subways;
        city.areas = city_data.areas;
        let result = await city_service.insert(city);
        ctx.body = result;
    } catch (err) {
        throw err;
    }
});

router.put('/city/:id', async (ctx, next) => {
    try {
        let city_id = ctx.params.id;
        let city = await city_service.findById(city_id);
        let city_data = await util.getCityData(city.pinyin);
        city.subways = city_data.subways;
        city.areas = city_data.areas;
        let result = await city_service.save(city);
        ctx.body = result;
    } catch (err) {
        throw err;
    }
});

// router.delete('/city/:id', async (ctx, next) => {
//     try {
//         let city_id = ctx.params.id;
//         let result = await city_service.delById(city_id);
//         ctx.body = result;
//     } catch (err) {
//         throw err;
//     }
// });
